import Result from './result.js';
import jwt from 'jsonwebtoken';
import { AsyncLocalStorage } from 'async_hooks';

const SECRET = process.env.JWT_SECRET || "siersi"
const options = { expiresIn: '3d' };

const asyncLocalStorage = new AsyncLocalStorage();

const TokenUtil = {
  generateToken(payload) {
    return jwt.sign(payload, SECRET, options);
  },

  verifyToken(token) {
    return jwt.verify(token, SECRET);
  },

  authenticateToken() {
    return (req, res, next) => {
      const Header = req.headers['authorization'] || req.headers['Authorization'];

      if (!Header || !Header.startsWith('Bearer ')) {
        return res.status(200).json(Result.error("身份信息无效"));
      }

      const token = Header.split(' ')[1].trim();

      if (!token) {
        return res.status(200).json(Result.error("身份信息无效"));
      }

      try {
        const decoded = this.verifyToken(token);
        asyncLocalStorage.run({ userId: decoded.id }, () => {
          req.user = decoded;
          next();
        });
      } catch (error) {
        return res.status(200).json(Result.error(error.message));
      }
    };
  },

  getCurrentUserId() {
    const store = asyncLocalStorage.getStore();
    if (!store?.userId) throw new Error('用户未认证');
    return store.userId;
  }
}

export default TokenUtil